//package com.bw.gmall.realtime.dws.app;
//
//import com.bw.gmall.realtime.common.base.BaseApp;
//import com.bw.gmall.realtime.common.constant.Constant;
//import org.apache.flink.streaming.api.datastream.DataStreamSource;
//import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
//import com.bw.gmall.realtime.common.bean.TradeSkuOrderBean;
//import com.bw.gmall.realtime.common.util.DateFormatUtil;
//import org.apache.flink.api.common.eventtime.WatermarkStrategy;
//import org.apache.flink.api.common.functions.MapFunction;
//import org.apache.flink.api.common.functions.ReduceFunction;
//import org.apache.flink.api.common.state.MapState;
//import org.apache.flink.api.common.state.MapStateDescriptor;
//import org.apache.flink.configuration.Configuration;
//import org.apache.flink.streaming.api.datastream.AsyncDataStream;
//import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
//import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
//import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
//import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
//import org.apache.flink.streaming.api.windowing.time.Time;
//import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
//import org.apache.flink.util.Collector;
//
//import java.math.BigDecimal;
//import java.time.Duration;
//import java.util.concurrent.TimeUnit;
//

/*
12.9交易域SKU粒度下单各窗口汇总表   异步缓存
 */

//public class DwsTradeSkuOrderAsyncCacheRealWindow extends BaseApp {
//    public static void main(String[] args) {
//        new DwsTradeSkuOrderAsyncCacheRealWindow().start(Constant.TOPIC_DWD_TRADE_ORDER_DETAIL,
//                Constant.DWS_TRADE_SKU_ORDER_WINDOW,4,10031);
//    }
//
//    @Override
//    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> dataStreamSource) {
////1. ETL清洗,并转化成JSON对象
//        SingleOutputStreamOperator<JSONObject> mapStream = dataStreamSource.map(new MapFunction<String, JSONObject>() {
//            @Override
//            public JSONObject map(String s) throws Exception {
//                if (s != null && !s.equals("")) {
//                    JSONObject jsonObject = JSON.parseObject(s);
//                    Long ts = jsonObject.getLong("ts");
//                    String id = jsonObject.getString("id");
//                    if (id != null && ts != null) {
//                        jsonObject.put("ts",ts * 1000);
//                        return jsonObject;
//                    }
//                }
//                return null;
//            }
//        });
//        //mapStream.print();
//
//        // 2.添加水位线WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness
//        // 3.按照id分组
//        // 4.状态编程聚合, 防止下游重复计算
//        SingleOutputStreamOperator<TradeSkuOrderBean> beanStream = mapStream.assignTimestampsAndWatermarks(
//                        WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(5))
//                                .withTimestampAssigner((json, timestamp) -> json.getLong("ts"))
//                                .withIdleness(Duration.ofSeconds(10)))
//                .keyBy(json -> json.getString("id"))
//                .process(new KeyedProcessFunction<String, JSONObject, TradeSkuOrderBean>() {
//                    private MapState<String, BigDecimal> mapState;
//
//                    @Override
//                    public void open(Configuration parameters) throws Exception {
//                        mapState = getRuntimeContext().getMapState(new MapStateDescriptor<>("mapState", String.class, BigDecimal.class));
//                    }
//
//                    @Override
//                    public void processElement(JSONObject jsonObject, KeyedProcessFunction<String, JSONObject, TradeSkuOrderBean>.Context context, Collector<TradeSkuOrderBean> collector) throws Exception {
//                        String id = jsonObject.getString("id");
//                        String sku_id = jsonObject.getString("sku_id");
//                        String sku_name = jsonObject.getString("sku_name");
//                        Long ts = jsonObject.getLong("ts");
//                        BigDecimal order_price = jsonObject.getBigDecimal("order_price");
//                        BigDecimal sku_num = jsonObject.getBigDecimal("sku_num");
//                        // 计算原始金额
//                        BigDecimal split_origin_amount = order_price.multiply(sku_num);
//                        BigDecimal split_total_amount = jsonObject.getBigDecimal("split_total_amount");
//                        BigDecimal split_activity_amount = jsonObject.getBigDecimal("split_activity_amount");
//                        BigDecimal split_coupon_amount = jsonObject.getBigDecimal("split_coupon_amount");
//
//                        BigDecimal split_origin_amount_state = mapState.get("split_origin_amount");
//                        BigDecimal split_total_amount_state = mapState.get("split_total_amount");
//                        BigDecimal split_activity_amount_state = mapState.get("split_activity_amount");
//                        BigDecimal split_coupon_amount_state = mapState.get("split_coupon_amount");
//
//                        split_origin_amount_state = split_origin_amount_state == null ? new BigDecimal(0) : split_origin_amount_state;
//                        split_total_amount_state = split_total_amount_state == null ? new BigDecimal(0) : split_total_amount_state;
//                        split_activity_amount_state = split_activity_amount_state == null ? new BigDecimal(0) : split_activity_amount_state;
//                        split_coupon_amount_state = split_coupon_amount_state == null ? new BigDecimal(0) : split_coupon_amount_state;
//
//                        // 往下游发的数据
//                        collector.collect(TradeSkuOrderBean.builder()
//                                .orderDetailId(id)
//                                .skuId(sku_id)
//                                .skuName(sku_name)
//                                .originalAmount(split_origin_amount.subtract(split_origin_amount_state))
//                                .activityReduceAmount(split_activity_amount.subtract(split_activity_amount_state))
//                                .couponReduceAmount(split_coupon_amount.subtract(split_coupon_amount_state))
//                                .orderAmount(split_total_amount.subtract(split_total_amount_state))
//                                .ts(ts)
//                                .build());
//                        mapState.put("split_origin_amount", split_origin_amount);
//                        mapState.put("split_activity_amount", split_activity_amount);
//                        mapState.put("split_coupon_amount", split_coupon_amount);
//                        mapState.put("split_total_amount", split_total_amount);
//                    }
//                });
//        //beanStream.print();
//
//        // 5.以sku_id分组, 聚合数据
//        SingleOutputStreamOperator<TradeSkuOrderBean> resultStream = beanStream.keyBy(bean -> bean.getSkuId())
//                .window(TumblingEventTimeWindows.of(Time.seconds(5L)))
//                .reduce(new ReduceFunction<TradeSkuOrderBean>() {
//                    @Override
//                    public TradeSkuOrderBean reduce(TradeSkuOrderBean v1, TradeSkuOrderBean v2) throws Exception {
//                        v1.setOriginalAmount(v1.getOriginalAmount().add(v2.getOriginalAmount()));
//                        v1.setActivityReduceAmount(v1.getActivityReduceAmount().add(v2.getActivityReduceAmount()));
//                        v1.setCouponReduceAmount(v1.getCouponReduceAmount().add(v2.getOrderAmount()));
//                        return v1;
//                    }
//                }, new ProcessWindowFunction<TradeSkuOrderBean, TradeSkuOrderBean, String, TimeWindow>() {
//                    @Override
//                    public void process(String s, ProcessWindowFunction<TradeSkuOrderBean, TradeSkuOrderBean, String, TimeWindow>.Context context, Iterable<TradeSkuOrderBean> iterable, Collector<TradeSkuOrderBean> collector) throws Exception {
//                        TradeSkuOrderBean bean = iterable.iterator().next();
//                        bean.setStt(DateFormatUtil.tsToDateTime(context.window().getStart()));
//                        bean.setEdt(DateFormatUtil.tsToDateTime(context.window().getEnd()));
//                        bean.setCurDate(DateFormatUtil.tsToDate(System.currentTimeMillis()));
//                        collector.collect(bean);
//                    }
//                });
//        //resultStream.print();
//
//        // 6.异步缓存关联维度
//        //先关联sku_info
//        SingleOutputStreamOperator<TradeSkuOrderBean> skuInfoStream = AsyncDataStream.unorderedWait(
//                resultStream, new DimAsyncFunction<TradeSkuOrderBean>("dim_sku_info") {
//                    @Override
//                    public String getDimId(TradeSkuOrderBean tradeSkuOrderBean) {
//                        return tradeSkuOrderBean.getSkuId();
//                    }
//
//                    @Override
//                    public void setDim(TradeSkuOrderBean tradeSkuOrderBean, JSONObject dimInfo) {
//                        tradeSkuOrderBean.setSpuId(dimInfo.getString("spu_id"));
//                        tradeSkuOrderBean.setTrademarkId(dimInfo.getString("tm_id"));
//                        tradeSkuOrderBean.setCategory3Id(dimInfo.getString("category3_id"));
//                    }
//                }, 100, TimeUnit.SECONDS);
//
//        skuInfoStream.print();
//
//
//        //再关联base_trademark
////        SingleOutputStreamOperator<TradeSkuOrderBean> baseTrademarkStream = AsyncDataStream.unorderedWait(skuInfoStream,
////                new RichAsyncFunction<TradeSkuOrderBean, TradeSkuOrderBean>() {
////            private StatefulRedisConnection<String, String> redisAsyncConnection;
////            private AsyncConnection hBaseAsyncConnection;
////
////            @Override
////            public void open(Configuration parameters) throws Exception {
////                hBaseAsyncConnection = HbaseUtil.getHBaseAsyncConnection();
////                redisAsyncConnection = RedisUtil.getRedisAsyncConnection();
////            }
////
////            @Override
////            public void close() throws Exception {
////                hBaseAsyncConnection.close();
////                redisAsyncConnection.close();
////            }
////
////            @Override
////            public void asyncInvoke(TradeSkuOrderBean tradeSkuOrderBean, ResultFuture<TradeSkuOrderBean> resultFuture) throws Exception {
////                String trademarkId = tradeSkuOrderBean.getTrademarkId();
////                String table = "dim_base_trademark";
////                String redisKey = RedisUtil.getRedisKey(table, trademarkId);
////                //先查找redis
////                CompletableFuture.supplyAsync(new Supplier<String>() {
////                    @Override
////                    public String get() {
////                        String dimInfo = null;
////                        RedisFuture<String> stringRedisFuture = redisAsyncConnection.async().get(redisKey);
////                        try {
////                            dimInfo = stringRedisFuture.get();
////                        } catch (InterruptedException e) {
////                            e.printStackTrace();
////                        } catch (ExecutionException e) {
////                            e.printStackTrace();
////                        }
////                        return dimInfo;
////                    }
////                }).thenApplyAsync(new Function<String, JSONObject>() {
////                    @Override
////                    public JSONObject apply(String dimInfo) {
////                        JSONObject jsonObject = null;
////                        if (dimInfo == null || dimInfo.length() == 0){
////                            try {
////                                jsonObject = HbaseUtil.getAsyncCells(hBaseAsyncConnection, Constant.HBASE_NAMESPACE, table, trademarkId);
////                                redisAsyncConnection.async().setex(redisKey,24 * 3600,jsonObject.toJSONString());
////                            } catch (IOException e) {
////                                e.printStackTrace();
////                            }
////                        } else {
////                            jsonObject = JSON.parseObject(dimInfo);
////                        }
////                        return jsonObject;
////                    }
////                }).thenAccept(new Consumer<JSONObject>() {
////                    @Override
////                    public void accept(JSONObject dimBaseTrademark) {
////                        if (dimBaseTrademark != null){
////                            tradeSkuOrderBean.setTrademarkName(dimBaseTrademark.getString("tm_name"));
////                        } else {
////                            System.out.println("没有查到维度数据:" + table + ":" + trademarkId);
////                        }
////                        resultFuture.complete(Collections.singletonList(tradeSkuOrderBean));
////                    }
////                });
////            }
////        }, 100, TimeUnit.SECONDS);
////
////        baseTrademarkStream.print();
////
////
////        //再关联spu
////        SingleOutputStreamOperator<TradeSkuOrderBean> spuInfoStream = AsyncDataStream.unorderedWait(baseTrademarkStream, new RichAsyncFunction<TradeSkuOrderBean, TradeSkuOrderBean>() {
////            private StatefulRedisConnection<String, String> redisAsyncConnection;
////            private AsyncConnection hBaseAsyncConnection;
////
////            @Override
////            public void open(Configuration parameters) throws Exception {
////                hBaseAsyncConnection = HbaseUtil.getHBaseAsyncConnection();
////                redisAsyncConnection = RedisUtil.getRedisAsyncConnection();
////            }
////
////            @Override
////            public void close() throws Exception {
////                hBaseAsyncConnection.close();
////                redisAsyncConnection.close();
////            }
////            @Override
////            public void asyncInvoke(TradeSkuOrderBean tradeSkuOrderBean, ResultFuture<TradeSkuOrderBean> resultFuture) throws Exception {
////                String spuId = tradeSkuOrderBean.getSpuId();
////                String table = "dim_spu_info";
////                String redisKey = RedisUtil.getRedisKey(table, spuId);
////                // 先查询redis
////                CompletableFuture.supplyAsync(new Supplier<String>() {
////                    @Override
////                    public String get() {
////                        String dimInfo = null;
////                        RedisFuture<String> stringRedisFuture = redisAsyncConnection.async().get(redisKey);
////                        try {
////                            dimInfo = stringRedisFuture.get();
////                        } catch (InterruptedException e) {
////                            e.printStackTrace();
////                        } catch (ExecutionException e) {
////                            e.printStackTrace();
////                        }
////                        return dimInfo;
////                    }
////                }).thenApplyAsync(new Function<String, JSONObject>() {
////                    JSONObject jsonObject = null;
////                    @Override
////                    public JSONObject apply(String dimInfo) {
////                        if (dimInfo == null && dimInfo.length() == 0){
////                            try {
////                                jsonObject = HbaseUtil.getAsyncCells(hBaseAsyncConnection, Constant.HBASE_NAMESPACE, table, spuId);
////                                redisAsyncConnection.async().setex(redisKey,24 * 3600,jsonObject.toJSONString());
////                            } catch (IOException e) {
////                                e.printStackTrace();
////                            }
////                        } else{
////                            jsonObject = JSON.parseObject(dimInfo);
////                        }
////                        return jsonObject;
////                    }
////                }).thenAccept(new Consumer<JSONObject>() {
////                    @Override
////                    public void accept(JSONObject dimSkuInfo) {
////                        if(dimSkuInfo != null){
////                            tradeSkuOrderBean.setSpuName(dimSkuInfo.getString("spu_name"));
////                        } else {
////                            System.out.println("没有查到维度数据:" + table + ":" + spuId);
////                        }
////                        resultFuture.complete(Collections.singletonList(tradeSkuOrderBean));
////                    }
////                });
////            }
////        }, 100, TimeUnit.SECONDS);
////
////        //再关联base_category3
////        SingleOutputStreamOperator<TradeSkuOrderBean> baseCategory3Stream = AsyncDataStream.unorderedWait(spuInfoStream, new RichAsyncFunction<TradeSkuOrderBean, TradeSkuOrderBean>() {
////            private StatefulRedisConnection<String, String> redisAsyncConnection;
////            private AsyncConnection hBaseAsyncConnection;
////
////            @Override
////            public void open(Configuration parameters) throws Exception {
////                hBaseAsyncConnection = HbaseUtil.getHBaseAsyncConnection();
////                redisAsyncConnection = RedisUtil.getRedisAsyncConnection();
////            }
////
////            @Override
////            public void close() throws Exception {
////                hBaseAsyncConnection.close();
////                redisAsyncConnection.close();
////            }
////            @Override
////            public void asyncInvoke(TradeSkuOrderBean tradeSkuOrderBean, ResultFuture<TradeSkuOrderBean> resultFuture) throws Exception {
////                String category3Id = tradeSkuOrderBean.getCategory3Id();
////                String table = "dim_base_category3";
////                String redisKey = RedisUtil.getRedisKey(table, category3Id);
////                //先查询redis
////                CompletableFuture.supplyAsync(new Supplier<String>() {
////                    @Override
////                    public String get() {
////                        String dimInfo = null;
////                        RedisFuture<String> stringRedisFuture = redisAsyncConnection.async().get(redisKey);
////                        try {
////                            dimInfo = stringRedisFuture.get();
////                        } catch (InterruptedException e) {
////                            e.printStackTrace();
////                        } catch (ExecutionException e) {
////                            e.printStackTrace();
////                        }
////                        return dimInfo;
////                    }
////                }).thenApplyAsync(new Function<String, JSONObject>() {
////                    @Override
////                    public JSONObject apply(String dimInfo) {
////                        JSONObject jsonObject = null;
////                        if (dimInfo == null && dimInfo.length() == 0){
////                            try {
////                                jsonObject = HbaseUtil.getAsyncCells(hBaseAsyncConnection,Constant.HBASE_NAMESPACE,table,category3Id);
////                                redisAsyncConnection.async().setex(redisKey,24 *3600,jsonObject.toJSONString());
////                            } catch (IOException e) {
////                                e.printStackTrace();
////                            }
////                        } else {
////                            jsonObject = JSON.parseObject(dimInfo);
////                        }
////                        return jsonObject;
////                    }
////                }).thenAccept(new Consumer<JSONObject>() {
////                    @Override
////                    public void accept(JSONObject dimBaseCategory3) {
////                        if (dimBaseCategory3 != null){
////                            tradeSkuOrderBean.setCategory2Id(dimBaseCategory3.getString("category2_id"));
////                            tradeSkuOrderBean.setCategory3Name(dimBaseCategory3.getString("name"));
////                        } else {
////                            System.out.println("没有查到维度数据:" + table + ":" + category3Id);
////                        }
////                        resultFuture.complete(Collections.singletonList(tradeSkuOrderBean));
////                    }
////                });
////            }
////        }, 100, TimeUnit.SECONDS);
////
////        //再关联base_category2
////        SingleOutputStreamOperator<TradeSkuOrderBean> baseCategory2Stream = AsyncDataStream.unorderedWait(baseCategory3Stream, new RichAsyncFunction<TradeSkuOrderBean, TradeSkuOrderBean>() {
////            private StatefulRedisConnection<String, String> redisAsyncConnection;
////            private AsyncConnection hBaseAsyncConnection;
////
////            @Override
////            public void open(Configuration parameters) throws Exception {
////                hBaseAsyncConnection = HbaseUtil.getHBaseAsyncConnection();
////                redisAsyncConnection = RedisUtil.getRedisAsyncConnection();
////            }
////
////            @Override
////            public void close() throws Exception {
////                hBaseAsyncConnection.close();
////                redisAsyncConnection.close();
////            }
////            @Override
////            public void asyncInvoke(TradeSkuOrderBean tradeSkuOrderBean, ResultFuture<TradeSkuOrderBean> resultFuture) throws Exception {
////                String category2Id = tradeSkuOrderBean.getCategory2Id();
////                String table = "dim_base_category2";
////                String redisKey = RedisUtil.getRedisKey(table, category2Id);
////                //先查询redis
////                CompletableFuture.supplyAsync(new Supplier<String>() {
////                    @Override
////                    public String get() {
////                        String dimInfo = null;
////                        RedisFuture<String> stringRedisFuture = redisAsyncConnection.async().get(redisKey);
////                        try {
////                            dimInfo = stringRedisFuture.get();
////                        } catch (InterruptedException e) {
////                            e.printStackTrace();
////                        } catch (ExecutionException e) {
////                            e.printStackTrace();
////                        }
////                        return dimInfo;
////                    }
////                }).thenApplyAsync(new Function<String, JSONObject>() {
////                    @Override
////                    public JSONObject apply(String dimInfo) {
////                        JSONObject jsonObject = null;
////                        if (dimInfo == null && dimInfo.length() == 0){
////                            try {
////                                jsonObject = HbaseUtil.getAsyncCells(hBaseAsyncConnection,Constant.HBASE_NAMESPACE,table,category2Id);
////                                redisAsyncConnection.async().setex(redisKey,24 *3600,jsonObject.toJSONString());
////                            } catch (IOException e) {
////                                e.printStackTrace();
////                            }
////                        } else {
////                            jsonObject = JSON.parseObject(dimInfo);
////                        }
////                        return jsonObject;
////                    }
////                }).thenAccept(new Consumer<JSONObject>() {
////                    @Override
////                    public void accept(JSONObject dimBaseCategory2) {
////                        if (dimBaseCategory2 != null){
////                            tradeSkuOrderBean.setCategory2Id(dimBaseCategory2.getString("category1_id"));
////                            tradeSkuOrderBean.setCategory3Name(dimBaseCategory2.getString("name"));
////                        } else {
////                            System.out.println("没有查到维度数据:" + table + ":" + category2Id);
////                        }
////                        resultFuture.complete(Collections.singletonList(tradeSkuOrderBean));
////                    }
////                });
////            }
////        }, 100, TimeUnit.SECONDS);
////
////        //再关联base_category1
////        SingleOutputStreamOperator<TradeSkuOrderBean> baseCategory1Stream = AsyncDataStream.unorderedWait(baseCategory2Stream, new RichAsyncFunction<TradeSkuOrderBean, TradeSkuOrderBean>() {
////            private StatefulRedisConnection<String, String> redisAsyncConnection;
////            private AsyncConnection hBaseAsyncConnection;
////
////            @Override
////            public void open(Configuration parameters) throws Exception {
////                hBaseAsyncConnection = HbaseUtil.getHBaseAsyncConnection();
////                redisAsyncConnection = RedisUtil.getRedisAsyncConnection();
////            }
////
////            @Override
////            public void close() throws Exception {
////                hBaseAsyncConnection.close();
////                redisAsyncConnection.close();
////            }
////
////            @Override
////            public void asyncInvoke(TradeSkuOrderBean tradeSkuOrderBean, ResultFuture<TradeSkuOrderBean> resultFuture) throws Exception {
////
////                String category1Id = tradeSkuOrderBean.getCategory1Id();
////                String table = "dim_base_category1";
////                String redisKey = RedisUtil.getRedisKey(table, category1Id);
////                //先查询redis
////                CompletableFuture.supplyAsync(new Supplier<String>() {
////                    @Override
////                    public String get() {
////                        String dimInfo = null;
////                        RedisFuture<String> stringRedisFuture = redisAsyncConnection.async().get(redisKey);
////                        try {
////                            dimInfo = stringRedisFuture.get();
////                        } catch (InterruptedException e) {
////                            e.printStackTrace();
////                        } catch (ExecutionException e) {
////                            e.printStackTrace();
////                        }
////                        return dimInfo;
////                    }
////                }).thenApplyAsync(new Function<String, JSONObject>() {
////                    @Override
////                    public JSONObject apply(String dimInfo) {
////                        JSONObject jsonObject = null;
////                        if (dimInfo == null && dimInfo.length() == 0){
////                            try {
////                                jsonObject = HbaseUtil.getAsyncCells(hBaseAsyncConnection,Constant.HBASE_NAMESPACE,table,category1Id);
////                                redisAsyncConnection.async().setex(redisKey,24 *3600,jsonObject.toJSONString());
////                            } catch (IOException e) {
////                                e.printStackTrace();
////                            }
////                        } else {
////                            jsonObject = JSON.parseObject(dimInfo);
////                        }
////                        return jsonObject;
////                    }
////                }).thenAccept(new Consumer<JSONObject>() {
////                    @Override
////                    public void accept(JSONObject dimBaseCategory1) {
////                        if (dimBaseCategory1 != null){
////                            tradeSkuOrderBean.setCategory3Name(dimBaseCategory1.getString("name"));
////                        } else {
////                            System.out.println("没有查到维度数据:" + table + ":" + category1Id);
////                        }
////                        resultFuture.complete(Collections.singletonList(tradeSkuOrderBean));
////                    }
////                });
////            }
////        }, 100, TimeUnit.SECONDS);
////
//////        baseCategory1Stream.print();
////
////        //写入doris
////        //synResult.map(new DorisMapFunction<>())
////        //        .sinkTo(FlinkSinkUtil.getDorisSink(Constant.DWS_TRADE_SKU_ORDER_WINDOW));
////
////        try {
////            env.execute();
////        } catch (Exception e) {
////            e.printStackTrace();
////        }
//
//
//    }
//}
